/*
 * Created on 8 mars 2005
 */
package clustering.implementations;
import clustering.framework.*;
//import javax.xml.parsers.*;
import org.w3c.dom.*;

import java.io.*;

/**
 * @author Tudor.Ionescu@supelec.fr

HTML2PresentationEngine

This class creates a representation of an XML tree using HTML tables and different colors but the result is different from that of the HTMLPresentationEngine class.

 */
public class HTML2PresentationEngine implements IPresentationEngine {
	String htmlHeader = "<html><body style=\"font-family: arial; font-size: 8pt;\"><table cellpadding=0 cellspacing=0><tr>";
	String htmlBody = "";
	String htmlFooter = "</tr></table></body></html>";
	String htmlContent = "";
	//Hashtable table = new Hashtable();
	String [][] table = null;
	int offset;
	public void ParseAndDisplay(String sName, Document xmlTree, String [] fileNames, String outputFilePath)throws Exception{
		table = new String[fileNames.length*2][fileNames.length];
		htmlContent = "<td><table cellpadding=0 border=1 cellspacing=1>";
		offset = 0;
		GenerateTable(xmlTree.getFirstChild(),0,fileNames);
		for(int j=0;j<table.length;j++){
			htmlContent += "<tr>";
			for(int k=0;k<table.length/2;k++){
				if(table[j][k]!=null){
					htmlContent += "<td>" + table[j][k] + "</td>";
				}else{
					htmlContent += "<td>&nbsp;</td>";
				}
			}
			htmlContent += "</tr>";
		}
		htmlContent += "</table></td>";
		htmlBody += htmlContent;
		
		FileOutputStream fos = new FileOutputStream(outputFilePath);
		fos.write(htmlHeader.getBytes());
		fos.write(htmlBody.getBytes());
		fos.write(htmlFooter.getBytes());
		fos.close();
	}

	void GenerateTable(Node xmlNode, int depth, String [] fileNames){
		if(!xmlNode.hasChildNodes()){
			// terminal node
			offset += 2;
			String sId = xmlNode.getAttributes().getNamedItem("id").getNodeValue();
			int id = Integer.parseInt(sId);
			String sFileName = "";
			if(fileNames[id].indexOf("\\")!=-1){
				sFileName = fileNames[id].substring(fileNames[id].lastIndexOf("\\")+1);
			}else if(fileNames[id].indexOf("/")!=-1){
				sFileName = fileNames[id].substring(fileNames[id].lastIndexOf("/")+1);
			}else sFileName = fileNames[id];
			table[offset][depth] = sFileName;
		}else{
			// intermediary node
			for(int i=0;i<xmlNode.getChildNodes().getLength();i++){
				GenerateTable(xmlNode.getChildNodes().item(i),depth+1,fileNames);
			}
			offset -= 1;			
			table[offset][depth] = "x";
		}
	}
}
